<template>
  <div :class="styles['return-goods-detail']" v-loading="pageLoading">
    <DrawerHeader title="退货入库订单详情页" @close="emit('close')"/>
    <DrawerInfo :ul-props="['logistics', 'mail']" :state="state.info"/>
    <div class="ato-detail-title-bar ato-mt-18">
      <b class="ato-mr-6">1、退货的销售订单UID：</b>
      <el-input v-if="isWrite" v-model="state.orderUID" placeholder="请输入" clearable style="width: 220px"/>
      <span v-else>{{ state.orderUID }}</span>
    </div>
    <div class="ato-detail-title-bar ato-mt-18">
      <b class="ato-mr-6">2、入库订单类型：</b>
      <span>退货入库</span>
      <div class="ato-ml-60">
        <b>签收卡牌数量：</b>
        <el-input v-if="isWrite" v-model="state.cardAmount" placeholder="请输入" clearable style="width: 220px"/>
        <span v-else>{{ state.cardAmount }}</span>
      </div>
    </div>
    <div class="ato-flex-center-both ato-padding-12">
      <b>3、单张卡牌入库：</b>
      <div class="ato-flex" v-if="!isWrite">
        <el-button class="ato-w160 ato-mr-12" >打印本单卡牌标签</el-button>
        <el-checkbox v-model="allCheck.checked" :indeterminate="allCheck.isIndeterminate" @change="handleCheckedAll">全选</el-checkbox>
      </div>
    </div>
    <PackageList
        ref="packageListRef"
        :table="table"
        :loading="loading"
        @handleWriteCardId="(row, $index) => writeChange(row, $index, 'cardId')"
        @handleWriteRatingNo="(row, $index) => writeChange(row, $index, 'ratingNo')"
        @handleChecked="handleChecked"
        @handleDelete="handleDelete"
    />
    <div v-if="isWrite" :class="styles['row-add']"><circle-plus :class="styles['icon']" @click="state.cardAmount ++"/><p>新增卡牌录入记录</p></div>
    <div class="ato-flex-jc-end ato-mb-32 ato-mt-24" v-if="!isWrite">
      <el-button type="primary" size="large" class="ato-w160" @click="batchPutStore">批量确认入库</el-button>
    </div>
    <div class="ato-flex-jc-center ato-mt-18">
      <el-button v-if="isWrite" type="primary" @click="next" size="large" class="ato-w160" :disabled="nextDisabled">下一步</el-button>
      <el-button v-if="!isWrite" @click="emit('close')" size="large" class="ato-w160 ato-mr-48">返回</el-button>
      <el-button v-if="!isWrite" type="primary" size="large" class="ato-w160">打印入库单</el-button>
    </div>
  </div>
</template>

<script setup name="ReturnGoodsDetail">
import {computed, onUnmounted, reactive, ref, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import { CirclePlus } from '@element-plus/icons-vue'
import { DrawerHeader, DrawerInfo, PackageList } from '@/components'
import columnsMap from '@/components/PackageList/columns'
import {getInOrderDetailApi} from '@/service/enterStore'
import {batchAddReturnCardApi, cardStockApi, queryCardInfoApi} from '@/service/card'

const emit = defineEmits(['close'])
const props = defineProps({
  orderNo: String,
  trackingNo: String
})

// 步骤key 'write填写' => 'confirm确定'
const stepProp = ref('write')
const isWrite = computed(() => stepProp.value === 'write')

const packageListRef = ref(null)

// 详情页loading
const pageLoading = ref(false)
// 页面数据
const state = reactive({
  trackingNo: '', // 物流单号
  orderUID: props.orderNo || '', // 退货的销售订单UID
  cardAmount: '', // 签收卡牌数量
  info: '' // 基本信息
})
// 全选按钮操作
const allCheck = reactive({
  checked: false, // 全选
  isIndeterminate: false, // 半选
  checkedRows: [] // 已选行数据
})
// loading
const loading = ref(false)
// 表格
const table = reactive({
  columns: computed(() => columnsMap.get(isWrite.value ? 20 : 21)),
  rows: [],
  attrs: {
    align: 'center'
  }
})
// 下一步按钮状态
const nextDisabled = computed(() => {
  return !table.rows.some(row => row.cardId && row.ratingNo)
})

// 获取详情数据
async function getDetailState () {
  pageLoading.value = true
  const res = await getInOrderDetailApi({
    orderNo: state.orderUID
  })
  if(res.code === __code) {
    const data = res.data
    state.info = data
    state.cardAmount = data.actualCount || 5
    state.trackingNo = data.trackingNo || ''
  }
  pageLoading.value = false
}

// 卡牌uid/评级号码 填写
async function writeChange (row, index, prop) {
  const res = await queryCardInfoApi({
    [prop]: row[prop]
  })
  if (res.code === __code) {
    table.rows[index] = Object.assign(table.rows[index], res.data)
  } else {
    ElMessage.warning('库内无此卡牌记录\n请联系线上客服沟通处理！')
    table.rows[index].cardId = ''
    table.rows[index].ratingNo = ''
  }
}

// 卡牌数量改变
function cardAmountChange (val) {
  const counter = val - table.rows.length
  // 只有当输入的值大于表格数据length时新增空行
  if(counter > 0) {
    const voidRows = Array.from({length: counter}, () => ({
      cardImg: '',
      cardId: '',
      cardName: '',
      rating: '',
      score: '',
      ratingNo: '',
      cardStatus: '',
      userWmsId: ''
    }))
    table.rows = table.rows.concat(voidRows)
  } else {
    // 小于表格数据length时切割原数据
    table.rows = [...table.rows].slice(0, table.rows.length + counter)
  }
}

// 删除
function handleDelete (row, $index) {
  const message = (row.cardId || row.ratingNo) ? `请确认是否删除" ${row.cardId || row.ratingNo} "此条记录?` : `请确认是否删除"第${$index + 1}条"记录`
  ElMessageBox.confirm(message, '删除提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  }).then(() => {
    table.rows.splice($index, 1)
    ElMessage({
      type: 'success',
      message: '已删除该条记录'
    })
  })
}

// 下一步
async function next () {
  const unVoidRows = table.rows.filter(row => row.cardId && row.ratingNo)
  pageLoading.value = true
  const res = await batchAddReturnCardApi({
    cardList: unVoidRows,
    trackingNo: state.trackingNo,
    orderNo: state.orderUID
  })
  if (res.code === __code) {
    // 跳转确定内容
    stepProp.value = 'confirm'
    table.rows = unVoidRows.map(row => ({...row, checked: false}))
  }
  pageLoading.value = false
}

// 操作复选框单选
function handleChecked ({allChecked, isIndeterminate, checkedRows}) {
  allCheck.checked = allChecked
  allCheck.isIndeterminate = isIndeterminate
  allCheck.checkedRows = checkedRows
}
// 操作全选/全不选
function handleCheckedAll (val) {
  packageListRef.value.handleCheckedAll(val)
}

// 批量入库确认
async function batchPutStore () {
  // 没选择时
  if (allCheck.checkedRows.length === 0) return ElMessage.warning('请勾选需要处理的卡牌！')
  const cardIds = allCheck.checkedRows.map(row => row.cardId)
  const res = await cardStockApi({cardIds, orderNo: state.orderUID})
  if (res.code === __code) {
    ElMessage.success('入库成功！')
  }
}

// 监听id变化更换数据
const unwatch = [
  watch(() => state.orderUID, () => {
    if(state.orderUID) getDetailState()
  }, {
    immediate: true
  }),
  watch(() => state.cardAmount, () => {
    cardAmountChange(state.cardAmount)
  }, {
    immediate: true
  })
]

onUnmounted(() => {
  // 取消监听
  unwatch.forEach(wa => wa())
})
</script>

<style lang="less" src="./index.less" module="styles"></style>
